<template>
  <div>
    <a-row style="position: absolute; top: 0; bottom: 3px; width: 100%">
      <a-col span="18">
    <div  class="h-full relative">
      <AMapComp class="h-full" :polygons="polygons" ref="amapRef" :markers="markers" :zoom="16"/>
      <div class="absolute bottom-0 left-0 bg-white/50 p-2 text-xs rounded-rt-lg">
        <div class="text-sm mb-2 font-bold">地块:</div>
        <div  v-for="item in polygons">
          <div  class="flex    mt-2  cursor-pointer">
            <div  class="border rounded-sm mr-2 w-10 h-4" :style="{'background-color':item.fillColor,'border-color':item.strokeColor}">
            </div>
            <div>
             <div>  {{ item.extData.name }}</div>
              <div class="flex items-center space-x-2 ">
                <div>产品：</div>
              <div v-for="p in item.extData.plans">{{ p.productNo_dictText }}</div>
            </div>
            </div>

          </div>

        </div>

      </div>
    </div>
      </a-col>
    <!--引用表格-->
      <a-col span="6" style="background: #ffffff;">
        <div style="background: #f0f2f5;padding-top: 8px;">
        <a-form
          style="margin: 0 8px 8px;background:#ffffff;padding: 10px"
          :model="formModel"
        >
          <a-row>
            <a-col :span="24">
              <a-form-item
                style="margin-bottom: unset"
                label="计划编号"
                name="planId"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-input v-model:value="formModel.planId" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

         <BasicTable @register="registerTable"
                     style="min-height: 71vh"
                     @row-click="rowClick"

         >
             <!--操作栏-->
           <template #time="{ record }">
             <span>{{ !record.startTime?"":(record.startTime.length>10?record.startTime.substr(0,10):record.startTime)}}</span>
             <br>
             <span>{{ !record.stopTime?"":(record.stopTime.length>10?record.stopTime.substr(0,10):record.stopTime)}}</span>
           </template>
            <template #action="{ record }">
              <span></span>
      <!--        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>-->
            </template>
            <!--字段回显插槽-->
            <template #htmlSlot="{text}">
               <div v-html="text"></div>
            </template>
            <!--省市区字段回显插槽-->
            <template #pcaSlot="{text}">
               {{ getAreaTextByCode(text) }}
            </template>
            <template #fileSlot="{text}">
               <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
               <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
            </template>
          </BasicTable>
        </div>
      </a-col>
    </a-row>
    <!-- 表单区域 -->
    <TGrowPlanModal @register="registerModal" @success="handleSuccess"></TGrowPlanModal>
    <Desc @register="registerDesc"></Desc>
  </div>
</template>

<script lang="ts" name="TGrowPlan-tGrowPlan" setup>
import AMapComp from '/@/components/AMap/AMap.vue'
import {ref, computed, unref, reactive, watch, onMounted} from 'vue';
import {BasicTable, useTable, TableAction, SorterResult} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import TGrowPlanModal from './components/TGrowPlanModal.vue'
  import {columns, searchFormSchema} from './TGrowPlan.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl} from './TGrowPlan.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { list as PoltList } from '/@/views/basic-information/region/TPlot.api.ts';
import { Modal } from 'ant-design-vue';

import Desc from "./components/Desc.vue";
  const rightActions = [
    {name:'新增计划',handler(){
      handleAdd()
    }},
  ];

  // Form model
  let formModel = reactive({
      planId: null,
  });
  // 详情内容
  const [registerDesc, { openModal: openDescInfo }] = useModal();
  const polygons = ref([])
  const markers = ref<any>([]);
  const tableHeight = ref('76.5vh')
  //注册model
  const [registerModal, {openModal}] = useModal();
  const getPolt  = (records)=>{
    PoltList({ pageSize:10000}).then(res => {
      markers.value = [];
      polygons.value = res.records.map((item) => {
        const plan = records.filter(a=>a.plotId==item.id);
        // 对于同一个计划，只保留一个
        const uniquePlans = plan.filter((v,i,a)=>a.findIndex(t=>(t.planId === v.planId))===i);
        const json = JSON.parse(item.polygon);
        const polygon = json ? json[0] || json : [];
        item.polygon = Object.assign({},polygon)
        item.plans = plan;
        polygon.extData = item;
        polygon.events = {
          onClick:(event) => {
            // handleAdd(item);
          }
        }
        
        if (uniquePlans.length) {
          polygon.rightActions = [
            ...uniquePlans.map((p)=>{
              return {
                name:'编辑计划：'+p.planId,
                handler(){
                  handleEdit(p)
                }
              }
            }) ,
          ]
        } else {
          polygon.rightActions = [
            {name:'新增计划',handler(){
              handleAdd(item)
            }}
          ]
        }
        
        // 构建产品图片显示
        let uniquePlanImages = plan.reduce((acc, cur) => {
          if (!acc[cur.product.no]) {
            // 如果 productImage 是 null 或者 undefined，跳过这个图片
            if (cur.product.logo != null) {
              // acc[cur.product.no] = '<img style="width: 100%;height: 100%;" src="' + cur.product.logo + '" alt="Image">';
              acc[cur.product.no] =  cur.product.logo
            }
          }
          return acc;
        }, {});

        let planImages = Object.values(uniquePlanImages)[0];

        markers.value.push({
          // lnglat:[
          //   item.centerGravity && item.centerGravity.latitude?item.centerGravity.latitude : (item.polygon && item.polygon.paths ? (Math.min(...item.polygon.paths.map(item => item[0])) + Math.max(...item.polygon.paths.map(item => item[0]))) / 2 : undefined),
          //   item.centerGravity && item.centerGravity.longitude?item.centerGravity.longitude : (item.polygon && item.polygon.paths ? (Math.min(...item.polygon.paths.map(item => item[1])) + Math.max(...item.polygon.paths.map(item => item[1]))) / 2 : undefined)
          // ], 
          lnglat: getCenterPoint(item.polygon.paths),
          address:planImages || '',customContent:true

        })
        return polygon;
      })
      
      if (markers.value.length) {
        amapRef?.value.setCenter(markers.value[0].lnglat)
      }
    })
  }
  const getCenterPoint = (coordinates) => {
    let totalLat = 0;
    let totalLng = 0;
  
    for (let i = 0; i < coordinates.length; i++) {
      totalLat += coordinates[i][0];
      totalLng += coordinates[i][1];
    }
  
    let centerLat = totalLat / coordinates.length;
    let centerLng = totalLng / coordinates.length;
  
    return [centerLat, centerLng];
  }
  var loaded = false;
  //注册table数据
  const { tableContext } = useListPage({
      tableProps:{
          title: '',
          api: list,
          afterFetch: (res) => {
          getPolt(res)
           if( !loaded ){
            loaded = true
             setTimeout(()=>{
               // getPolt(res)
             },500)
           }
          },
          columns,
          showTableSetting: false,
          canResize:false,
          searchInfo:formModel,
          useSearchForm:false,
          formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
             fieldMapToTime: [['planTime', ['startTime', 'stopTime'], 'YYYY-MM-DD'],
               ['actualTime', ['actualStartTime', 'actualStopTime'], 'YYYY-MM-DD']]
            },
          actionColumn: false
      },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext
  // 观察表单模型变化
  let timeout;
  watch(formModel, () => {
  if (timeout) clearTimeout(timeout);

  timeout = setTimeout(() => {
    console.log('formModel changed', formModel);
    // 在这里调用你的方法，例如reload()
    reload();
    }, 300); // 300毫秒后触发
  }, { deep: true });
  // 地图引用
  const amapRef = ref();
  // 选择的地块
  const choose = ref();
  const originalOptions = ref();


  // 表格行点击事件
  const rowClick = async (record, index, event) => {
    const target = amapRef.value.searchOverlays((overlay) => overlay.getExtData().id == record.plotId)
    if (target) {
      if (choose.value&&originalOptions.value){
        choose.value.setOptions(originalOptions.value);
      }
      choose.value = target;
      originalOptions.value = target.getOptions();
      target.setOptions({
        fillColor: '#7ED321',  // 新的填充颜色
        strokeColor: '#920783',  // 新的边框颜色
        fillOpacity: 0.6 // 不透明的填充
      });
      amapRef.value.showOverlay(target)
    }
  };
   /**
    * 新增事件
    */
  function handleAdd(record?:Recordable) {
    console.log(record)
     openModal(true, {
       isUpdate: false,
       showFooter: true,
       plotId:record?.id
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(datas,plot) {
     openDescInfo(true, {
       plot:plot,
       datas,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '删除',
           onClick: handleDelete.bind(null, record),
         }
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return []
   }

</script>

<style scoped>
.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
}
</style>
